<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="下单时间" prop="timeRange">
        <el-date-picker
          v-model="queryParams.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 360px;"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

      <el-form-item prop="status">
        <el-radio-group
          v-model="queryParams.status"
          @change="handleQuery"
          class="radio-group-horizontal"
        >
          <el-radio-button
            v-for="dict in dict.type.sc_order_status"
            :key="dict.value"
            :label="dict.value"
          >
            <div class="badge-container">
              {{ dict.label }}
              <el-badge
                v-if="dict.value == 2"
                :value="orderNumber.toBeConfirmed || 0"
                class="custom-badge"
                type="danger"
              />
              <el-badge
                v-else-if="dict.value == 3"
                :value="orderNumber.confirmed || 0"
                class="custom-badge"
                type="danger"
              />
              <el-badge
                v-else-if="dict.value == 4"
                :value="orderNumber.deliveryInProgress || 0"
                class="custom-badge"
                type="danger"
              />
            </div>
          </el-radio-button>

          <el-radio-button :label="null">全部订单</el-radio-button>
        </el-radio-group>
      </el-form-item>


    </el-form>


    <el-table v-loading="loading" :data="ordersList">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center">
        <!--        每页的序号都从1开始-->
        <!--        <template slot-scope="scope">-->
        <!--          {{ scope.$index + 1 }}-->
        <!--        </template>-->
        <!--        不间断序号-->
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="订单号" align="center" prop="number"/>
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sc_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phone"/>
      <el-table-column label="收货人" align="center" prop="consignee"/>
      <el-table-column label="订单取消原因" align="center" prop="cancelReason"/>
      <el-table-column label="订单拒绝原因" align="center" prop="rejectionReason"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="170">
        <template slot-scope="scope">
          <div class="btn_box">
            <!-- 合并操作组 -->
            <div class="action-group compact">
              <el-button v-if="scope.row.status === 2"
                         type="success"
                         size="mini"
                         link
                         class="compact-btn"
                         @click="orderAccept(scope.row)"
                         v-hasPermi="['order:order:edit']">
                接单
              </el-button>
              <el-button v-if="scope.row.status === 3"
                         type="success"
                         size="mini"
                         link
                         class="compact-btn"
                         @click="deliveryOrComplete(3, scope.row.id)"
                         v-hasPermi="['order:order:edit']">
                出餐
              </el-button>
              <el-button v-if="scope.row.status === 4"
                         type="success"
                         size="mini"
                         link
                         class="compact-btn"
                         @click="deliveryOrComplete(4, scope.row.id)"
                         v-hasPermi="['order:order:edit']">
                完成
              </el-button>
              <el-button v-if="scope.row.status === 2"
                         type="danger"
                         size="mini"
                         link
                         class="compact-btn"
                         @click="orderReject(scope.row)"
                         v-hasPermi="['order:order:edit']">
                拒单
              </el-button>
              <el-button v-if="[1, 3, 4, 5].includes(scope.row.status)"
                         type="danger"
                         size="mini"
                         link
                         class="compact-btn"
                         @click="cancelOrder(scope.row)"
                         v-hasPermi="['order:order:edit']">
                取消
              </el-button>


              <el-button type="primary"
                         size="mini"
                         link
                         class="blueBtn compact-btn"
                         @click="goDetail(scope.row)"
                         v-hasPermi="['order:order:edit']">
                查看
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页组件-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--    查看详情弹窗-->
    <el-dialog :title="title" :visible.sync="open" width="690px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-divider content-position="center">订单明细信息</el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ form.number || '无' }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <dict-tag :options="dict.type.sc_order_status" :value="form.status"/>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <dict-tag :options="dict.type.sc_order_pay_method" :value="form.payMethod"/>
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <dict-tag :options="dict.type.sc_order_pay_status" :value="form.payStatus"/>
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ parseTime(form.orderTime) || '无' }}</el-descriptions-item>
          <el-descriptions-item label="结账时间">{{ parseTime(form.checkoutTime) || '无' }}</el-descriptions-item>
          <el-descriptions-item label="实收金额">¥{{ (form.amount || 0).toFixed(2) }}</el-descriptions-item>
          <!--          <el-descriptions-item label="预计送达">{{-->
          <!--              parseTime(form.estimatedDeliveryTime) || '无'-->
          <!--            }}-->
          <!--          </el-descriptions-item>-->
          <!--          <el-descriptions-item label="送达时间">{{ parseTime(form.deliveryTime) || '无' }}</el-descriptions-item>-->

          <el-descriptions-item label="客户备注信息" :span="2">{{ form.remark || '无' }}</el-descriptions-item>
          <el-descriptions-item
            v-if="form.cancelReason"
            label="取消原因"
            :span="2"
          >
            {{ form.cancelReason }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="form.rejectionReason"
            label="拒单原因"
            :span="2"
          >
            {{ form.rejectionReason }}
          </el-descriptions-item>
        </el-descriptions>
        <el-divider content-position="center">菜品明细信息</el-divider>
        <el-table :data="orderDetailList" ref="orderDetailList">
          <el-table-column label="序号" align="center" width="50">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="菜品" prop="name" width="150">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column label="口味" prop="dishFlavor" width="150">
            <template slot-scope="scope">{{ scope.row.dishFlavor }}</template>
          </el-table-column>
          <el-table-column label="数量" prop="number" width="150">
            <template slot-scope="scope">{{ scope.row.number }}</template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="150">
            <template slot-scope="scope">¥{{ scope.row.amount.toFixed(2) }}</template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>

    <!--    取消订单/拒单 弹窗-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="commonDialogVisible"
      width="500px"
      append-to-body
    >
      <div style="margin-bottom: 20px;">
        <el-radio-group v-model="selectedReason">
          <el-radio
            v-for="item in currentReasons"
            :key="item.value"
            :label="item.value"
            style="display: block; margin: 10px 0;"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>

        <el-input
          v-if="selectedReason === 0"
          v-model="otherReasonText"
          type="textarea"
          :placeholder="reasonPlaceholder"
          rows="3"
          style="margin-top: 10px;"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="commonDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCommonConfirm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getOrderDetailPageAPI,
  queryOrderDetailByIdAPI,
  completeOrderAPI,
  deliveryOrderAPI,
  orderCancelAPI,
  orderRejectAPI,
  orderAcceptAPI,
  getOrderListByAPI
} from "@/api/smartcanteen/order";

export default {
  name: "Orders",
  dicts: ['sc_order_pay_status', 'sc_order_status', 'sc_order_pay_method'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 对话框状态管理
      activeDialog: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      ordersList: [],
      // 订单数量
      orderNumber: { // 初始化为对象
        toBeConfirmed: 0,
        confirmed: 0,
        deliveryInProgress: 0
      },
      // 订单详情
      detailDialogVisible: false,
      // 订单详情列表
      orderDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        number: null,
        status: null,
        userId: null,
        timeRange: [],
        phone: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 取消订单原因
      cancelReasons: [
        {value: 1, label: '订单量较多，暂时无法接单'},
        {value: 2, label: '菜品已销售完，暂时无法接单'},
        {value: 3, label: '餐厅已打烊，暂时无法接单'},
        {value: 0, label: '其他'}
      ],
      // 拒单原因
      rejectReasons: [
        {value: 1, label: '订单量较多，暂时无法接单'},
        {value: 2, label: '菜品已销售完，暂时无法接单'},
        {value: 3, label: '骑手不足无法配送'},
        {value: 4, label: '客户电话取消'},
        {value: 0, label: '其他'}
      ],
      currentOrder: null,
      commonDialogVisible: false,
      dialogType: null, // 'cancel' 或 'reject'
      currentReasons: [],
      selectedReason: null,
      otherReasonText: '',
      reasonPlaceholder: '请输入具体原因',
    };
  },
  created() {
    this.getOrderNumber();
    this.getList();
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      getOrderDetailPageAPI(this.queryParams).then(response => {
        this.ordersList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 订单状态下订单数量 */
    getOrderNumber() {
      getOrderListByAPI().then(response => {
        // 改为逐个属性更新
        this.$set(this.orderNumber, 'toBeConfirmed', response.data.toBeConfirmed)
        this.$set(this.orderNumber, 'confirmed', response.data.confirmed)
        this.$set(this.orderNumber, 'deliveryInProgress', response.data.deliveryInProgress)
      })
    },
    /** 查看按钮操作 */
    goDetail(row) {
      this.reset();

      queryOrderDetailByIdAPI(row.id).then(response => {
        this.form = response.data;
        this.orderDetailList = response.data.orderDetailList.map(order => {
          const dishId = order.dishId;
          return ({
            name: order.name || '无',
            dishId: dishId || '无',
            setmealId: order.setmealId || '无',
            dishFlavor: order.dishFlavor || '无',
            amount: order.amount || '无',
            number: order.number || '无',
          });
        });
        this.open = true;
        this.title = "查看订单";
      });
    },
    // 关闭其他对话框
    closeOtherDialogs() {
      this.cancelDialogVisible = false;
      this.activeDialog = null;
    },
    // 接单按钮操作
    orderAccept(row) {
      this.$modal.confirm('确认接单编号为"' + row.number + '"的订单吗？').then(() => {
        return orderAcceptAPI({id: row.id}) // 传递订单ID参数
      }).then(response => {
        this.$modal.msgSuccess("接单成功");
        this.getList(); // 刷新订单列表
        this.getOrderNumber(); // 刷新顶部状态数量统计
      }).catch(error => {
        // 这里可以添加错误处理逻辑
        if (error !== 'cancel') { // 排除用户取消确认弹窗的情况
          this.$modal.msgError("接单失败：" + (error.message || "未知错误"));
        }
      });
    },
    // 出餐按钮操作
    deliveryOrComplete(status, id) {
      const apiMap = {
        3: {api: deliveryOrderAPI, action: '出餐'},
        4: {api: completeOrderAPI, action: '完成'}
      }

      const {api, action} = apiMap[status] || {api: () => Promise.reject('无效状态'), action: '操作'}

      this.$modal.confirm(`确认${action}订单吗？`)
        .then(() => api({id})) // 统一参数格式
        .then(() => {
          this.$modal.msgSuccess(`${action}成功`)
          this.getList()
          this.getOrderNumber()
        })
        .catch(error => {
          if (error === 'cancel') return
          const msg = error.message?.includes('Network Error')
            ? '网络连接异常'
            : error.message || '未知错误'
          this.$modal.msgError(`${action}失败：${msg}`)
        })
    },
    // 取消/拒单按钮操作
    computed: {
      dialogTitle() {
        return this.dialogType === 'cancel' ? '取消订单原因' : '拒单原因'
      }
    },
// 统一打开弹窗方法
    openReasonDialog(type, row) {
      this.dialogType = type
      this.currentOrder = row
      this.currentReasons = type === 'cancel' ? this.cancelReasons : this.rejectReasons
      this.reasonPlaceholder = type === 'cancel' ? '请输入取消原因' : '请输入拒单原因'
      this.selectedReason = null
      this.otherReasonText = ''
      this.commonDialogVisible = true
    },

    // 统一确认处理
    handleCommonConfirm() {
      if (this.selectedReason === null) {
        this.$message.warning('请选择原因')
        return
      }

      if (this.selectedReason === 0 && !this.otherReasonText.trim()) {
        this.$message.warning(this.reasonPlaceholder)
        return
      }

      const reasonObj = this.currentReasons.find(item => item.value === this.selectedReason)
      const reasonText = reasonObj.value === 0 ?
        this.otherReasonText :
        reasonObj.label

      const apiMap = {
        cancel: {
          api: orderCancelAPI,
          successMsg: "取消成功"
        },
        reject: {
          api: orderRejectAPI,
          successMsg: "拒单成功"
        }
      }

      const {api, successMsg} = apiMap[this.dialogType]

      api({
        id: this.currentOrder.id,
        [this.dialogType === 'cancel' ? 'cancelReason' : 'rejectionReason']: reasonText
      }).then(() => {
        this.$modal.msgSuccess(successMsg)
        this.commonDialogVisible = false
        this.getList()
        this.getOrderNumber()
      })
    },
    // 取消订单按钮
    cancelOrder(row) {
      this.openReasonDialog('cancel', row)
    },

    // 拒单按钮
    orderReject(row) {
      this.openReasonDialog('reject', row)
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        number: null,
        status: null,
        userId: null,
        addressBookId: null,
        orderTime: null,
        checkoutTime: null,
        payMethod: null,
        payStatus: null,
        amount: null,
        remark: null,
        phone: null,
        address: null,
        userName: null,
        consignee: null,
        cancelReason: null,
        rejectionReason: null,
        cancelTime: null,
        estimatedDeliveryTime: null,
        deliveryStatus: null,
        deliveryTime: null,
        packAmount: null,
        tablewareNumber: null,
        tablewareStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      if (this.queryParams.timeRange && this.queryParams.timeRange.length === 2) {
        this.queryParams.beginTime = this.queryParams.timeRange[0];
        this.queryParams.endTime = this.queryParams.timeRange[1];
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + ids + '"的数据项？').then(function () {
        return delOrders(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

  }
}
;
</script>
<style>

/* Radio Button 组的居中和样式 */
.radio-group-horizontal {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  width: 100%;
  margin-left: 7px;
}


.radio-group-horizontal .el-radio-button__inner {
  padding: 12px 2px;
  font-size: 15px;
  min-width: 168px;
  height: 40px;
  font-weight: bold;
  white-space: nowrap;
  position: relative;
}

.radio-group-horizontal .el-radio-button.is-active .el-radio-button__inner {
  background-color: #409EFF;
  color: white;
}

/* 保持其他表单元素左对齐 */
.el-form {
  width: 100%;
  text-align: left;
}

.el-radio-button:first-child .el-radio-button__inner {
  border-left: 1px solid #DCDFE6;
  border-radius: 10px 0 0 10px;
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
}

.el-radio-button:last-child .el-radio-button__inner {
  border-radius: 0 10px 10px 0;
}

/* 调整徽标位置 */
.badge-wrapper .el-badge__content {
  top: 8px;
  right: 20px;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  min-width: 18px;
  padding: 0 4px;
  border: 2px solid #fff; /* 添加白色边框避免重叠 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影提升层次感 */
}

.el-badge__content--danger {
  background-color: #ff4d4f; /* 更鲜艳的红色 */
}

/* 新增独立样式 */
.custom-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  z-index: 10;
}

.badge-container {
  position: relative;
  display: inline-block;
  padding-right: 20px; /* 给气泡留出空间 */
}

.btn_box {
  display: flex;
  justify-content: center;
  width: 100%;
}

.action-group {
  display: inline-flex;
  align-items: center;
  padding: 2px 6px;
  border-radius: 4px;
}

.compact-btn {
  padding: 0 8px !important;
  font-size: 14px !important;
  height: 28px;
  border-radius: 5px;
}


/* 移动端适配 */
@media screen and (max-width: 768px) {
  .action-group {
    padding: 2px;
  }

  .compact-btn {
    padding: 0 4px !important;
  }
}
</style>
